/**
 * 
 */
package cn.ad.server.web.spring.service.actions;


import cn.ad.server.common.utils.BrowserUtils;
import cn.ad.server.common.utils.CodecUtils;
import cn.ad.server.common.utils.GdtWinPriceDecoder;
import cn.ad.server.common.utils.IPUtils;
import cn.ad.server.persistence.*;
import cn.ad.server.web.spring.model.AdRequest;
import cn.ad.server.web.spring.model.AdResponse;
import cn.ad.server.web.spring.service.actions.command.WinNoticeCommand;
import cn.ad.server.web.spring.service.actions.context.IPContext;
import cn.ad.server.web.spring.service.actions.presentation.WinNoticePresentation;
import cn.ad.server.domain.IPDetail;
import cn.ad.server.domain.ad.AdMaterial;
import cn.ad.server.domain.ad.GuidValueObject;
import cn.ad.server.domain.ad.Strategy;
import cn.ad.server.domain.enumration.ResponseStatusCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * RTB bid winnotice 请求处理调度类
 * @author Administrator
 * @since v1.0
 * 不推荐使用 V2 版本移动到 {@link AdTrackingAction}
 */

@Deprecated
@Component("winnoticeAction")
public class WinnoticeRequestAction implements IAdRequestAction {
	
	// FIXME 改为系统参数配置
	@Value("${channel.adview.ekey}")
	private String ekey;

	@Value("${channel.adview.ikey}")
	private String ikey;

	@Value("${channel.gdt.token}")
	private String gdtToken;

	@Autowired
	private AdSpaceRepository adSpaceRepository;

	@Autowired
	private CreativeRepository creativeRepository;

	@Autowired
	private StrategyRepository strategyRepository;

	@Autowired
	private ConfigRepository configRepository;

	@Autowired
	private AdTemplateRepository adTemplateRepository;

	@Autowired
	private PlatformRepository platformRepository;

	@Autowired
	private CampaignRepository campaignRepository;

	@Autowired
	private TagRepository tagRepository;
	
	@Autowired
	private GuidRepository guidRepository;
	
	/* (non-Javadoc)
	 * @see cn.ad.server.web.spring.service.IAdService#doRequest(cn.ad.server.web.request.AdRequest)
	 */
	@Override
	public AdResponse doRequest(AdRequest request) {
		return null;
	}
	
	
	public WinNoticePresentation makeWinNotice(WinNoticeCommand aCommand)
			throws NumberFormatException, InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException,
            NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
		WinNoticePresentation wcp = new WinNoticePresentation();
		wcp.setPlatformId(aCommand.getPlatform_id());
		wcp.setRequestTimestamp(System.currentTimeMillis());
		wcp.setRequestIp(aCommand.getIp());
		wcp.setServerId(IPUtils.getHostName());
		wcp.setAdxType(StringUtils.isBlank(aCommand.getPlatform_id()) ? 0 : Integer.valueOf(aCommand.getPlatform_id()));
		GuidValueObject guidVo = guidRepository.findGuidVo(aCommand.getGuid());

		wcp.setGuid(aCommand.getGuid());
		wcp.setExceptionType(0);
		wcp.setUa(aCommand.getUa());
		wcp.setEventType(4);
		if (guidVo != null) {
			wcp.setAdFormat(guidVo.getFid());
			wcp.setTemplateId(guidVo.getTemplateId());

			IPDetail ipDetail = IPContext.instance().getIPDetail(IPUtils.convertIPToLong(guidVo.getIp()));
			if (ipDetail != null) {
				wcp.setCountryId(ipDetail.getCountryId());
				wcp.setStateId(ipDetail.getStateId());
				wcp.setCityId(ipDetail.getCityId());
				wcp.setAreaId(ipDetail.getDistrictId());
			}

			wcp.setAdspaceId(guidVo.getAid());
			wcp.setMuniqueType(String.valueOf(guidVo.getMuniqueType()));
			wcp.setMuniqueId(guidVo.getMuniqueId());
			wcp.setMobOps(String.valueOf(guidVo.getOperator()));
			wcp.setBrand(guidVo.getBrand());
			wcp.setModel(guidVo.getPlatform());
			wcp.setOs(String.valueOf(guidVo.getOs()));
			wcp.setConnType(guidVo.getNetwork());
			wcp.setDeviceType(guidVo.getDeviceType());
			wcp.setLatitude(String.valueOf(guidVo.getLatitude()));
			wcp.setLongitude(String.valueOf(guidVo.getLongitude()));
			wcp.setIp(guidVo.getIp());
			wcp.setStrategyId(guidVo.getSid());

			wcp.setCreativeId(guidVo.getCid());
			wcp.setMaterialId(guidVo.getMid());

			if (!StringUtils.isEmpty(guidVo.getDeviceSize()) && guidVo.getDeviceSize().contains("*")) {
				String[] d = guidVo.getDeviceSize().split("\\*");
				wcp.setScreenWidth(Integer.valueOf(d[0]));
				wcp.setScreenHeight(Integer.valueOf(d[1]));
			}
			AdMaterial adMaterial = this.creativeRepository.findAdMaterialById(guidVo.getMid());
			if (adMaterial != null) {
				wcp.setCreativeHeight(adMaterial.getAdSize().getHeight());
				wcp.setCreativeWidth(adMaterial.getAdSize().getWidth());
			}

			wcp.setMac(guidVo.getMac());
			wcp.setMac1(guidVo.getMac1());
			wcp.setImei(guidVo.getImei());
			wcp.setAnid(guidVo.getAnid());
			wcp.setAaid(guidVo.getAaid());
			wcp.setIdfa(guidVo.getIdfa());
			wcp.setUdid(guidVo.getUdid());
			wcp.setDuid(guidVo.getDuid());

			wcp.setImeisha1(guidVo.getImeisha1());
			wcp.setDpidsha1(guidVo.getDpidsha1());
			wcp.setMacsha1(guidVo.getMacsha1());
			wcp.setImeimd5(guidVo.getImeimd5());
			wcp.setDpidmd5(guidVo.getDpidmd5());
			wcp.setMacmd5(guidVo.getMacmd5());
			wcp.setCustomId(guidVo.getCustomId());
			wcp.setOpenUdid(guidVo.getOpenUdid());

		} else {

			// TODO GUID失效的时候 记录
			if (StringUtils.isNotEmpty(aCommand.getSid())) {
				wcp.setStrategyId(Long.parseLong(aCommand.getSid()));
			}

			if (StringUtils.isNotEmpty(aCommand.getCid())) {
				wcp.setCreativeId(Long.parseLong(aCommand.getCid()));
			}

			if (StringUtils.isNotEmpty(aCommand.getMid())) {
				wcp.setMaterialId(Long.parseLong(aCommand.getMid()));
			}
		}
		wcp.setBrowser(BrowserUtils.getBrowser(aCommand.getUa()));

		Strategy s = strategyRepository.findById(Integer.valueOf(aCommand.getSid()));

		if (s != null) {
			wcp.setCampaignId(s.getCampaign().getId());
		} else {
			wcp.setExceptionType(ResponseStatusCode.INVALID_STRATEGY.getValue());
		}

		if (!StringUtils.isBlank(aCommand.getWin_price())) {
			double price = 0.0d;
			if (aCommand.getAdxType() == 3) {
				GdtWinPriceDecoder decoder = new GdtWinPriceDecoder();
				String sss = decoder.DecodePrice(aCommand.getWin_price(), this.gdtToken.substring(0, 16));
				BigDecimal bd = new BigDecimal(Double.valueOf(sss));
				price = bd.divide(new BigDecimal(100)).doubleValue();

			} else {
				BigDecimal bd = new BigDecimal(CodecUtils.decryptWinPrice(aCommand.getWin_price(), ekey, ikey));
				price = bd.divide(new BigDecimal(10000 * 1000)).doubleValue();
			}
			wcp.setPayment(price);
		}
		return wcp;
	}
	
}
